#! /usr/bin/env python
#-*- encoding: utf-8 -*-
"""
Beercamp_ret.py
http://31o5.com/
"""

import sys
import time
import base64, httplib, urllib, urllib2
from elementtree.ElementTree import *
from cElementTree import Element, ElementTree

class TwitterAPI:
    def __init__(self, username, password):
        # generate authentication header string
        self.authentication = { "Authorization": "Basic %s" 
            % base64.encodestring("%s:%s" % (username, password)).strip() }

        # create connection
        self.connection = httplib.HTTPConnection("twitter.com", 80)

    def update_status(self, status):
        # send post response with authenticated status
        param = urllib.urlencode({ "status": status })
        self.connection.request("POST", "/statuses/update.xml", param, self.authentication)
        response = self.connection.getresponse()
        return response.status

    def get_replies(self):
        self.connection.request("GET", "/statuses/replies.xml", '', self.authentication)
        response = self.connection.getresponse()
        return response.read()

#Twitter Login Information
username = sys.argv[1]
password = sys.argv[2]

#Login to Twitter
twitt = TwitterAPI(username, password)

#Get @reply and Re-Tweet
def retweet():                                      
    rep = twitt.get_replies()
    ret = ElementTree(fromstring(rep)) 
    root = ret.getroot()
    for elem in root[0].getiterator():
        if elem.tag in ["text"]:
            tweet = elem.text[10:]
            post = twitt.update_status(tweet) 

retweet()
